package com.wwwarehouse.carddesk.fragment.teamfragment.checkupclassfragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.bean.CardDeskGroupGetGroupBean;
import com.wwwarehouse.carddesk.bean.GroupHtmlDataBean;
import com.wwwarehouse.carddesk.bean.teambean.AllPowerDetailBean;
import com.wwwarehouse.carddesk.constant.CardDeskConstant;
import com.wwwarehouse.carddesk.custom_view.NewLineFlexLayout;
import com.wwwarehouse.carddesk.fragment.teamfragment.commenttargetweb.AgeingTargetFragmnent;
import com.wwwarehouse.carddesk.fragment.teamfragment.commenttargetweb.EfficiencyTargetFragmnent;
import com.wwwarehouse.carddesk.fragment.teamfragment.commenttargetweb.QualityTargetFragmnent;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.CircleImageView;
import com.wwwarehouse.common.custom_widget.button.StateButton;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ToastUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @创建者 chenchao.
 * @创建时间 2017/11/13 16:56
 * @描述 ${TODO}
 */

public class CheckUpClassFragment extends BaseFragment implements View.OnClickListener {

    private View                               mView;
    private StateLayout                        mStateLayout;
    private CircleImageView                    mCivLeadHead;
    private TextView                           mTvLeadName;
    private CircleImageView                    mCivHead;
    private TextView                           mTvName;
    private TextView                           mTvMore;
    private NewLineFlexLayout                  mLineFlexLayout;
    private LinearLayout                       mLlDetail;
    private TextView                           mTvTeamName;
    private BridgeWebView                      mBwWebView;
    private StateButton                        mBtConnect;
    private StateButton                        mBtBackTeam;
    private ImageView                          mIvAsk;
    private CardDeskGroupGetGroupBean.ListBean mBean;
    private LinearLayout                mLlHaveData;
    private LinearLayout                mLlNoData;
    private String mNewUrl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_check_up_class, container, false);
        initView();
        return mView;
    }

    private void initView() {

        mStateLayout = findView(mView, R.id.sl_layout);
        mCivLeadHead = findView(mView, R.id.civ_lead_head);
        mTvLeadName = findView(mView, R.id.tv_laed_name);
        mCivHead = findView(mView, R.id.civ_head);
        mTvName = findView(mView, R.id.tv_name);
        mTvMore = findView(mView, R.id.tv_more);
        mLineFlexLayout = findView(mView, R.id.new_line_layout);
        mLlDetail = findView(mView, R.id.ll_detail);
        mIvAsk = findView(mView, R.id.iv_ask);
        mTvTeamName = findView(mView, R.id.tv_team_name);
        mBwWebView = findView(mView, R.id.bw_web_view);
        mLlHaveData = findView(mView, R.id.ll_have_data);
        mLlNoData = findView(mView, R.id.ll_no_data);
        mBtConnect = findView(mView, R.id.bt_connect);
        mBtBackTeam = findView(mView, R.id.bt_back_team);

        mTvMore.setOnClickListener(this);
        mLlDetail.setOnClickListener(this);
        mBtConnect.setOnClickListener(this);
        mBtBackTeam.setOnClickListener(this);


    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof CheckUpClassFragment) {
            mActivity.setTitle(R.string.teamdesk_member);
        }
    }

    @Override
    public void requestDatas() {
        if (getArguments() != null) {
            mBean = getArguments().getParcelable("bean");
            BaseApplication.getApplicationInstance().displayImg(sp.getValue(Constant.sp_Face_Url), mCivLeadHead);
            mTvLeadName.setText(sp.getValue(Constant.sp_Person_Name));
            BaseApplication.getApplicationInstance().displayImg(mBean.getFaceUrl(), mCivHead);
            mTvName.setText(mBean.getPersonName());
            mTvTeamName.setText(String.format(mActivity.getResources().getString(R.string.teamdesk_team), mBean.getPersonName()));
        }

        //六个小条 请求权限
        Map<String, Object> powerMap = new HashMap<>();
        powerMap.put("authorityCode", 3);
        powerMap.put("authorizeTeamUserId", sp.getValue(Constant.sp_User_Id));
        powerMap.put("beauthorizedTeamUserId", mBean.getUserId());
        powerMap.put("page", 1);
        powerMap.put("size", 7);
        NoHttpUtils.httpPost(CardDeskConstant.GET_RELATIONAUITEM_INFO, powerMap, mOnResponseListener, 0);


        String env = sp.getValue(Constant.sp_Env, sp.getValue(Constant.sp_EnvDefault, Constant.ENV_DEFAULT));
        if (Constant.ENV_DEV.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_DEV;
        } else if (Constant.ENV_CIT.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_CIT;
        } else if (Constant.ENV_SIT.equals(env)) {
            mBaseUrl = "";
        } else if (Constant.ENV_UAT.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_UAT;
        } else if (Constant.ENV_RELEASE.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_RELEASE;
        } else if (Constant.ENV_CIT2.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_CIT2;
        }
        mNewUrl = mBaseUrl + CardDeskConstant.PATH_GROUP_PARTR_H5_URL;
        bundleBean = getArguments().getParcelable("bean");
        mBwWebView.loadUrl(mNewUrl);
        mStateLayout.showProgressView(true);
        mBwWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if(newProgress == 100){
                    mStateLayout.showContentView();
                }else{
                }
            }
        });
        registJsMethod();
    }

    private String mBaseUrl = "";
    private CardDeskGroupGetGroupBean.ListBean bundleBean;
    private String data;

    private void registJsMethod() {

        GroupHtmlDataBean bean = new GroupHtmlDataBean();
        bean.setToken(BaseApplication.sp.getValue(Constant.sp_Token));
        if(bundleBean != null ){
            bean.setRankingCompany(new String[]{bundleBean.getBuId()});
            bean.setRankingUser(new String[]{bundleBean.getUserId()});
            bean.setIsTriMember(0);
            if (mBean != null) {
                bean.setPrivilegeUp(new String[]{sp.getValue(Constant.sp_User_Id)});
                bean.setPrivilegeDown(new String[]{mBean.getUserId()});
            }

        }



        //        bean.setRankingCompany(new String[]{"10"});
        //        bean.setRankingUser(new String[]{"1"});
        //        bean.setIsTriMember(1);
        //        bean.setPrivilegeUp("");
        //        bean.setPrivilegeDown("");

        data = JSON.toJSON(bean).toString();

        //Js获取请求的参数
        mBwWebView.callHandler("getData", data, new CallBackFunction() {
            @Override
            public void onCallBack(String responseData) {
                ToastUtils.showToast(responseData);
            }
        });

        //隐藏StateLayout和ProgressDialog
        mBwWebView.registerHandler("hideProgress", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //                dismissProgressDialog();
                mStateLayout.showContentView();
            }
        });

        //显示progressDialog
        mBwWebView.registerHandler("showProgress", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //                showProgressDialog("正在加载...");
                mStateLayout.showProgressView(true);
            }
        });

        //显示错误信息
        mBwWebView.registerHandler("showErrorMsg", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //                dismissProgressDialog();
                //                toast("" + data);
                mStateLayout.showSystemView(true);
                mStateLayout.setSystemListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBwWebView.loadUrl(mNewUrl);
                        //        mBwWebView.loadUrl("http://192.168.72.177:8888/app/teamFrame/teamMember.html");
                        mStateLayout.showProgressView(true);
                    }
                });
            }
        });

        //显示没有数据view
        mBwWebView.registerHandler("showNotData", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mLlHaveData.setVisibility(View.GONE);
                //                dismissProgressDialog();
                mStateLayout.showContentView();
                mLlNoData.setVisibility(View.VISIBLE);
            }
        });

        //点击时效
        mBwWebView.registerHandler("gotoAging", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Bundle bundle = new Bundle();
                bundle.putInt("IsTriMember", 0);
                if (mBean != null) {
                    bundle.putStringArray("up",new String[]{sp.getValue(Constant.sp_User_Id)});
                    bundle.putStringArray("down",new String[]{mBean.getUserId()});
                }
                bundle.putParcelable("bean",bundleBean);
                AgeingTargetFragmnent fragment = new AgeingTargetFragmnent();
                fragment.setArguments(bundle);
                pushFragment(fragment);
            }
        });

        //点击效率
        mBwWebView.registerHandler("gotoEffective", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Bundle bundle = new Bundle();
                bundle.putInt("IsTriMember", 0);
                if (mBean != null) {
                    bundle.putStringArray("up",new String[]{sp.getValue(Constant.sp_User_Id)});
                    bundle.putStringArray("down",new String[]{mBean.getUserId()});
                }
                bundle.putParcelable("bean",bundleBean);
                EfficiencyTargetFragmnent fragmnent = new EfficiencyTargetFragmnent();
                fragmnent.setArguments(bundle);
                pushFragment( fragmnent );
            }
        });

        //点击品质
        mBwWebView.registerHandler("gotoQuality", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Bundle bundle = new Bundle();
                bundle.putInt("IsTriMember", 0);
                if (mBean != null) {
                    bundle.putStringArray("up",new String[]{sp.getValue(Constant.sp_User_Id)});
                    bundle.putStringArray("down",new String[]{mBean.getUserId()});
                }
                bundle.putParcelable("bean",bundleBean);
                QualityTargetFragmnent fragmnent = new QualityTargetFragmnent();
                fragmnent.setArguments(bundle);
                pushFragment(fragmnent);
            }
        });

    }
    
    private NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            try {
                switch (what) {
                    case 0:
                        if ("0".equals(commonClass.getCode())) {
                            AllPowerDetailBean allPowerDetailBean = JSON.parseObject(commonClass.getData().toString(), AllPowerDetailBean.class);
                            List<AllPowerDetailBean.ListBean> list = allPowerDetailBean.getList();

                            LayoutInflater inflater = LayoutInflater.from(mActivity);
                            mLineFlexLayout.setMaxLine(3);
                            if (list.size() > 6) {
                                mTvMore.setVisibility(View.VISIBLE);
                                for (int i = 0; i < 6; i++) {
                                    String itemName = list.get(i).getItemName();
                                    TextView tv = (TextView) inflater.inflate(R.layout.team_view_new_line_flex_layout, mLineFlexLayout, false);
                                    tv.setText(itemName);
                                    mLineFlexLayout.addView(tv);
                                }
                            } else {
                                for (int i = 0; i < list.size(); i++) {
                                    String itemName = list.get(i).getItemName();
                                    TextView tv = (TextView) inflater.inflate(R.layout.team_view_new_line_flex_layout, mLineFlexLayout, false);
                                    tv.setText(itemName);
                                    mLineFlexLayout.addView(tv);
                                }
                            }

                        }
                        break;
                    default:
                        break;
                }

            } catch (Exception e) {
                LogUtils.showLog(e.toString());
            }
        }

        @Override
        public void onFailed(String result, int what) {

        }

        @Override
        public void onFinish(int what) {

        }
    };

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_more) {
            Bundle bundle = new Bundle();
            bundle.putString("authorizeTeamUserId", sp.getValue(Constant.sp_User_Id));
            bundle.putString("beauthorizedTeamUserId", mBean.getUserId());
            AllPowerFragment allPowerFragment = new AllPowerFragment();
            allPowerFragment.setArguments(bundle);
            pushFragment(allPowerFragment);
        } else if (id == R.id.ll_detail) {
            PopUpUtils.showBubbleUpTeam(mIvAsk, mActivity, String.format(mActivity.getResources().getString(R.string.teamdesk_power_from), mBean.getPersonName(), mBean.getPersonName()), ConvertUtils.dip2px(mActivity, 11), 0);
        } else if (id == R.id.bt_connect) {
            if (!TextUtils.isEmpty(mBean.getMobile())) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mBean.getMobile()));
                startActivity(intent);
            }
        } else if (id == R.id.bt_back_team) {
            popFragment();
        }
    }
}
